package com.jiuyin.dianjing.ui.activity.setting;

import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.UserItemModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;

/**
 * 订阅
 */
public class SettingSubscriptionActivity extends BaseActivity {
    @BindView(R.id.rcv_page)
    SwipeRecyclerView mRcvPage;
    @BindView(R.id.srl_record_layout)
    SmartRefreshLayout mSrlRecordLayout;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView mEmptyText;
    @BindView(R.id.empty_image)
    ImageView mEmptyImage;

    private int mPageNum = PAGE_FIRST;
    private boolean loadEnd;
    private BaseRecyclerAdapter<UserItemModel> mAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_setting_my_subscription;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<UserItemModel>(R.layout.item_user) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, UserItemModel model, int position) {
                if (null != model) {
                    holder.text(R.id.tv_name, model.getNickname());
                    ImageView ivGame = holder.itemView.findViewById(R.id.img_header);
                    Glide.with(SettingSubscriptionActivity.this)
                            .load(model.getHeader())
                            .override(DisplayUtil.dp2px(SettingSubscriptionActivity.this, 27), DisplayUtil.dp2px(SettingSubscriptionActivity.this, 27))
                            .into(ivGame);
                }
            }
        };
        // 创建菜单：
        SwipeMenuCreator mSwipeMenuCreator = (leftMenu, rightMenu, position) -> {
            int height = ViewGroup.LayoutParams.WRAP_CONTENT;
            int width = getResources().getDimensionPixelSize(R.dimen.dp_40);
            SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
            deleteItem.setText(R.string.setting_collection_quit);
            deleteItem.setBackground(R.drawable.btn_red_bg);
            deleteItem.setTextColor(Color.WHITE);
            deleteItem.setWidth(width);
            deleteItem.setHeight(height);
            rightMenu.addMenuItem(deleteItem);
        };
        OnItemMenuClickListener menuClickListener = (menuBridge, position) -> {
            menuBridge.closeMenu();
            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
                mAdapter.remove(mAdapter.get(position));
            }
        };
        DefaultItemDecoration itemDecoration = new DefaultItemDecoration(ContextCompat.getColor(this, R.color.color_list_divider));
        mRcvPage.addItemDecoration(itemDecoration);
        mRcvPage.setSwipeMenuCreator(mSwipeMenuCreator);
        mRcvPage.setOnItemMenuClickListener(menuClickListener);
        mRcvPage.setAdapter(mAdapter);
        fetchData();
    }

    @Override
    protected void initView() {
        setTitle(R.string.my_subscription);
        mSrlRecordLayout.setRefreshHeader(new ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.colorAccent).setAccentColorId(android.R.color.white));
        mSrlRecordLayout.setEnableAutoLoadMore(true);
        mSrlRecordLayout.setOnRefreshListener(refreshLayout -> {
            loadEnd = false;
            mPageNum = PAGE_FIRST;
            mSrlRecordLayout.setEnableLoadMore(true);
            fetchData();
            mSrlRecordLayout.finishRefresh();
        });
        mSrlRecordLayout.setOnLoadMoreListener(refreshLayout -> {
            if (loadEnd) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                fetchData();
                refreshLayout.finishLoadMore();
            }
        });
        mEmptyText.setText(R.string.empty_tip);
        mEmptyImage.setImageResource(R.drawable.ic_empty);
    }

    private void fetchData() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_PAGE_NUM, mPageNum);
        JSONObject jsonObject = new JSONObject(data);
        ProgressDialogCallback progress = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                if (null != data && data.has(KEY_LIST)) {
                    List<UserItemModel> fansItemModels = new Gson().fromJson(data.getAsJsonArray(KEY_LIST), new TypeToken<List<UserItemModel>>() {
                    }.getType());
                    if (null != fansItemModels) {
                        int size = fansItemModels.size();
                        if (0 != size) {
                            onRefresh(fansItemModels);
                        }
                    }
                } else {
                    if (View.VISIBLE != mEmptyLayout.getVisibility()) {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFail(String msg) {
                LogUtil.log("SettingSubscriptionActivity onFail msg = " + msg);
            }

            @Override
            public void onError(String msg) {
                LogUtil.log("SettingSubscriptionActivity onError msg = " + msg);
            }
        };
        ServerApi.post(ApiEnum.APP_GET_USER_FANS_LIST_API.getUrl(), jsonObject, null,
                progress, d -> addDisposable(d), request);

    }

    public void onRefresh(List<UserItemModel> models) {
        int size = models.size();
        if (PAGE_FIRST == mPageNum) {
            mAdapter.refresh(models);
        } else {
            if (0 != size) {
                mAdapter.loadMore(models);
            }
        }
        if (size < PAGE_NUM) {
            loadEnd = true;
            mSrlRecordLayout.finishLoadMoreWithNoMoreData();
        }
        mPageNum++;
    }
}
